package com.android.sunflower.ui.mygarden

import android.os.Looper
import android.os.Message
import androidx.lifecycle.ViewModel
import com.android.sunflower.logic.Repository
import com.android.sunflower.logic.room.entities.Flower
import com.android.sunflower.logic.room.entities.PlantedF
import com.android.sunflower.utils.ThreadPool
import java.util.concurrent.Callable

class MyGardenViewModel:ViewModel() {
    val plantedFList= mutableListOf<PlantedF>()

    val plantedFInfoList= mutableListOf<Flower>()

    fun selectAll(){
        val task=object :Runnable{
            override fun run() {
                Looper.prepare()
                plantedFList.clear()
                plantedFInfoList.clear()
                plantedFList.addAll(Repository.selectAllPlatedF())
                for(pl in plantedFList){
                    plantedFInfoList.addAll(Repository.selectFlowerByName(pl.plantName!!))
                }
                val msg1=Message().apply {
                    what=MyGardenFragment.queryPlantedFSuccess
                }
                val msg2=Message().apply {
                    what=MyGardenFragment.queryPlantedFEmptyOrNull
                }

                if(!plantedFList.isEmpty()) MyGardenFragment.handler?.sendMessage(msg1)
                else MyGardenFragment.handler?.sendMessage(msg2)

                Looper.loop()
                MyGardenFragment.handler?.looper?.quitSafely()
            }
        }
        ThreadPool.exec.execute(task)
    }

    fun deleteItems(pls:List<PlantedF>){
        val task=object :Runnable{
            override fun run() {
                Looper.prepare()
                for(pl in pls){
                    Repository.deletePlantF(pl)
                }
                val msg=Message().apply {
                    what=MyGardenFragment.refreshListByDelete
                }
                MyGardenFragment.handler?.sendMessage(msg)
                Looper.loop()
                MyGardenFragment.handler?.looper?.quitSafely()
            }
        }
        ThreadPool.exec.execute(task)
    }

    fun updateItems(pls:List<PlantedF>){
        val task=object :Runnable{
            override fun run() {
                Looper.prepare()
                for(pl in pls){
                    Repository.updatePlatedF(pl)
                }
                val msg=Message().apply {
                    what=MyGardenFragment.refreshListByUpdate
                }
                MyGardenFragment.handler?.sendMessage(msg)
                Looper.loop()
                MyGardenFragment.handler?.looper?.quitSafely()
            }
        }
        ThreadPool.exec.execute(task)
    }
}